package db

import (
	"context"
	"fmt"
	"github.com/jackc/pgx/v5/pgxpool"
	"go.uber.org/zap"
	"internal_training_be/config"
	_ "internal_training_be/logger"
)

const (
	schema          = "s_training_system"
	adminTable      = "t_admin"
	employeeTable   = "t_employee"
	courseTable     = "t_course"
	enrollmentTable = "t_enrollment"
	feedbackTable   = "t_feedback"
	progressTable   = "t_training_progress"
)

var (
	logger = zap.L().Sugar()
	dbPool *pgxpool.Pool
)

type TableInfo struct {
	Name        string
	CreateQuery string
}

func init() {
	configReader, err := config.GetConfigReader()
	if err != nil {
		logger.Errorf("get config reader failed: %v", err)
		return
	}

	// 从配置文件中读取数据库连接配置
	host := configReader.GetString("dbms.host")
	port := configReader.GetString("dbms.port")
	user := configReader.GetString("dbms.user")
	pwd := configReader.GetString("dbms.pwd")
	dbname := configReader.GetString("dbms.db")

	// 构建连接字符串
	connString := fmt.Sprintf("postgres://%v:%v@%v:%v/%v", user, pwd, host, port, dbname)

	// 初始化数据库连接池
	dbPool, err = initDBPool(connString)
	if err != nil {
		logger.Errorf("init db pool failed: %v", err)
		return
	}

	// 获取数据库连接
	conn, err := GetDBConn()
	if err != nil {
		logger.Errorf("get db connection failed: %v", err)
		return
	}
	defer conn.Release()

	// 初始化模式
	err = initSchema(context.Background(), conn)
	if err != nil {
		logger.Errorf("init schema failed: %v", err)
		return
	}

	// 初始化表
	err = initTable(context.Background(), conn)
	if err != nil {
		logger.Errorf("init table failed: %v", err)
		return
	}

	// 初始化测试用户
	err = initTestUser(context.Background(), conn)
	if err != nil {
		logger.Errorf("init test user failed: %v", err)
		return
	}

	return
}
